package com.ray.base.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.builder.TemplateBuilder;
import com.ray.base.check.TemplateCheck;
import com.ray.base.service.BaseTemplateService;
import com.ray.base.table.dto.TemplateQueryDTO;
import com.ray.base.table.entity.BaseTemplate;
import com.ray.base.table.params.template.TemplateCreateParams;
import com.ray.base.table.params.template.TemplateEditParams;
import com.ray.base.table.params.template.TemplateQueryParams;
import com.ray.base.table.vo.template.TemplateVO;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 产品扩展属性相关服务
 * @Class: TemplateApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class TemplateApi {

    @Autowired
    private BaseTemplateService baseTemplateService;


    /**
     * 查询扩展属性列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<TemplateVO>> pageTemplates(CommonPage<TemplateQueryParams, Page<TemplateVO>> queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不存在");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<TemplateQueryDTO, BaseTemplate> commonPageBuilder = new CommonPageBuilder<>(TemplateQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<BaseTemplate> page = baseTemplateService.page(commonPageBuilder.bulid(), loginUser);
        List<BaseTemplate> customers = page.getRecords();
        //结果对象
        IPage<TemplateVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(customers)) {
            pageList.setRecords(customers.stream().map(sysTemplate -> {
                TemplateVO customerVO = new TemplateVO();
                BeanUtil.copyProperties(sysTemplate, customerVO);
                return customerVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询扩展属性列表信息--启用的扩展属性
     *
     * @param queryParams
     * @return
     */
    public Result<List<TemplateVO>> queryTemplates(TemplateQueryParams queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不存在");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        TemplateQueryDTO queryDTO = new TemplateQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<BaseTemplate> customers = baseTemplateService.list(queryDTO, loginUser);
        //查询对象
        List<TemplateVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(customers)) {
            list = customers.stream().map(sysTemplate -> {
                TemplateVO customerVO = new TemplateVO();
                BeanUtil.copyProperties(sysTemplate, customerVO);
                return customerVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建扩展属性
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createTemplate(TemplateCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        BaseTemplate materialTemplate = baseTemplateService.queryTemplateByProp(createParams.getProp(),createParams.getTemplateType(),loginUser);
        new TemplateCheck(materialTemplate).checkTemplateProp(null,"属性已经存在");
        TemplateBuilder customerBuilder = new TemplateBuilder();
        customerBuilder.append(createParams).appendComapnyCode(loginUser.getCompanyCode())
                .appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存扩展属性信息
        if (!baseTemplateService.save(customerBuilder.bulid())) {
            log.info("保存扩展属性接口异常,参数:{}", JSON.toJSONString(customerBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, customerBuilder.getCode());
    }

    /**
     * 编辑扩展属性
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editTemplate(TemplateEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        BaseTemplate materialTemplate = baseTemplateService.queryTemplateByProp(editParams.getProp(),editParams.getTemplateType(),loginUser);
        new TemplateCheck(materialTemplate).checkTemplateProp(editParams.getTemplateCode(),"属性已经存在");
        TemplateBuilder customerBuilder = new TemplateBuilder();
        customerBuilder.append(editParams).appendEdit(loginUser);
        //编辑扩展属性信息
        if (!baseTemplateService.edit(customerBuilder.bulid(), loginUser)) {
            log.info("编辑扩展属性接口异常,参数:{}", JSON.toJSONString(customerBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, customerBuilder.getCode());
    }


    /**
     * 删除扩展属性
     *
     * @param templateCode 扩展属性编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteTemplate(String templateCode) {
        ValidateUtil.hasLength(templateCode, "参数[templateCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        BaseTemplate sysTemplate = baseTemplateService.queryTemplateByTemplateCode(templateCode, loginUser);
        new TemplateCheck(sysTemplate).checkNull("属性不存在");
        TemplateBuilder customerBuilder = new TemplateBuilder();
        customerBuilder.appendCode(templateCode).appendEdit(loginUser).delete();
        //删除扩展属性信息
        if (!baseTemplateService.edit(customerBuilder.bulid(), loginUser)) {
            log.info("删除扩展属性接口异常,参数:{}", JSON.toJSONString(customerBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, customerBuilder.getCode());
    }

    /**
     * 开启扩展属性
     *
     * @param templateCode 扩展属性编码
     * @return Result
     */
    @Transactional
    public Result<String> openTemplate(String templateCode) {
        ValidateUtil.hasLength(templateCode, "参数[templateCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        BaseTemplate sysTemplate = baseTemplateService.queryTemplateByTemplateCode(templateCode, loginUser);
        new TemplateCheck(sysTemplate).checkNull("属性不存在");
        TemplateBuilder customerBuilder = new TemplateBuilder();
        customerBuilder.appendCode(templateCode).appendEdit(loginUser).open();
        //开启扩展属性信息
        if (!baseTemplateService.edit(customerBuilder.bulid(), loginUser)) {
            log.info("开启扩展属性接口异常,参数:{}", JSON.toJSONString(customerBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, customerBuilder.getCode());
    }

    /**
     * 开启扩展属性
     *
     * @param templateCode 扩展属性编码
     * @return Result
     */
    @Transactional
    public Result<String> closeTemplate(String templateCode) {
        ValidateUtil.hasLength(templateCode, "参数[templateCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        BaseTemplate sysTemplate = baseTemplateService.queryTemplateByTemplateCode(templateCode, loginUser);
        new TemplateCheck(sysTemplate).checkNull("属性不存在");
        TemplateBuilder customerBuilder = new TemplateBuilder();
        customerBuilder.appendCode(templateCode).appendEdit(loginUser).close();
        //关闭扩展属性信息
        if (!baseTemplateService.edit(customerBuilder.bulid(), loginUser)) {
            log.info("关闭扩展属性接口异常,参数:{}", JSON.toJSONString(customerBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, customerBuilder.getCode());
    }

    /**
     * 扩展属性详情
     *
     * @param templateCode 扩展属性编码
     * @return Result
     */
    public Result<TemplateVO> viewTemplate(String templateCode) {
        ValidateUtil.hasLength(templateCode, "参数[templateCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        BaseTemplate sysTemplate = baseTemplateService.queryTemplateByTemplateCode(templateCode, loginUser);
        new TemplateCheck(sysTemplate).checkNull("属性不存在");
        TemplateVO customerVO = new TemplateVO();
        BeanUtil.copyProperties(sysTemplate, customerVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, customerVO);
    }

}
